package com.mchat.communication.server;

import com.mchat.communication.server.initializer.CustomChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ChatServer {
    private static final int PORT = 8002;
    @Resource
    private CustomChannelInitializer initializer;

    public void start() {
        //boss线程
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //worker线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //netty服务,启动引擎
            ServerBootstrap bootstrap = new ServerBootstrap();
            //主从模式
            bootstrap.group(bossGroup, workerGroup)
                    //主线程处理类
                    .channel(NioServerSocketChannel.class)
                    //配置信息
                    .option(ChannelOption.SO_BACKLOG, 1024)// 针对主线程配置
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//子线程配置
                    //子线程的处理，Handler
                    .childHandler(initializer);
            //等待客户端连接
            ChannelFuture channelFuture = bootstrap.bind(PORT).sync();
            System.out.println("chat-server start. port " + PORT);
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
